package com.xiangwei.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;










import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.druid.util.StringUtils;
import com.xiangwei.dto.DropDownDto;
import com.xiangwei.entity.Image;
import com.xiangwei.entity.Vendor;
import com.xiangwei.service.IImageService;
import com.xiangwei.service.IProductService;
import com.xiangwei.service.IVendorService;
import com.xiangwei.util.Common;
import com.xiangwei.util.QiniuUtil;
import com.xiangwei.util.getDate;
import com.xiangwei.view.VendorView;

@Controller
@RequestMapping(value = "admin")
public class VendorController {
	private static final Logger logger = LoggerFactory
			.getLogger(VendorController.class);
	
	
	@Resource
	private IVendorService vendorService;
	@Resource
	private IProductService productService;
	@Resource
	private IImageService imageService;
	// 厂商LIST
	private List<Vendor> vendorList;
	// 厂商名称下拉框
	private List<DropDownDto> vendorNameList;

	private String vendorId;
	private int pageIndex = 0;
	private int pageCount = 3;

	/**
	 * 初始化查询厂商列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "vendorList", method = RequestMethod.GET)
	public String init(Model model) {
		Long id = null;
		pageIndex = 0;
		Map<Object, Object> paraMap = new HashMap<Object, Object>();
		paraMap.put("vendorId", id);
		paraMap.put("pageIndex", pageIndex);
		paraMap.put("pageCount", pageCount);// 每页显示多少条数据
		// 查询列表方法
		findVendorList(paraMap, model);
		return "admin/vendorList";
	}

	/**
	 * 查询厂商
	 * 
	 * @param vendorId
	 * @param page
	 *            判断分页 1-下一页，2-上一页
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "searchVendor", method = RequestMethod.GET)
	public String searchVendor(String vendorId, String pageStr, Model model) {
		Long id = null;
		if (!StringUtils.equals("0", vendorId)) {
			id = Long.parseLong(vendorId);
		}
		int page = Integer.parseInt(pageStr);
		// 分页查询判断
		if (page == 1) {
			pageIndex = pageIndex + pageCount;
		} else if (page == 2 && pageIndex > 0) {
			pageIndex = pageIndex - pageCount;
		} else if (page == 0) {
			pageIndex = 0;
		}
		Map<Object, Object> paraMap = new HashMap<Object, Object>();
		paraMap.put("vendorId", id);
		paraMap.put("pageIndex", pageIndex);
		paraMap.put("pageCount", pageCount);// 每页显示多少条数据
		// 查询列表方法
		findVendorList(paraMap, model);
		return "admin/vendorList";
	}

	/**
	 * 新增厂商
	 * 
	 * @return
	 */
	@RequestMapping(value = "insertVendor", method = RequestMethod.GET)
	public String insertVendor() {
		return "admin/addVendor";
	}

	/**
	 * 修改厂商
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "editVendor", method = RequestMethod.GET)
	public String editVendor(String id, Model model,
			HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		Integer vId = Integer.parseInt(id);
		VendorView vv = vendorService.selectVendorViewById(vId);
		model.addAttribute("vendorView", vv);
		short type = 0;
		Image img= new Image();//多图
		img.setPid(vId);
		img.setType(type);//厂商多图关联类型为0
		List<Image> imgList = imageService.getImagesByPidAndType(img);
		
		model.addAttribute("imageUrl", QiniuUtil.IMAGEURL);
		model.addAttribute("imgList", imgList);
		request.getSession().setAttribute("vendorId", vId);
		return "admin/vendorEdit";
	}

	/**
	 * 保存厂商信息
	 * 
	 * @param vendor
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "saveVendor", method = RequestMethod.POST)
	public String saveVendor(@RequestParam("file") MultipartFile file,
			@ModelAttribute Vendor vendor, Model model,String[] cName,String[] cValue,
			String[] eId,HttpServletRequest request) throws IOException {
	
		Integer vendorId = vendor.getId();
		// 设置删除标志以及时间参数的值
		if (!file.isEmpty()) {
			// 文件保存路径
			String fileNames = getDate.getStringFullDate()
					+ file.getOriginalFilename(); // 文件名称
			String filePath = request.getSession().getServletContext().getRealPath("/")
					+ "uploadImage/" + fileNames;
			// 如果不存在，则创建目录
			if (!new File(filePath).isDirectory()) {
				new File(filePath).mkdirs();
			}
			try {
				// 转存文件
				File fileSave = new File(filePath);
				file.transferTo(fileSave);
				vendor.setLogo(fileNames);
				String success = QiniuUtil.upload(filePath, fileNames); // 上传到七牛云服务
				if (success != null) {
					fileSave.delete(); // 如果上传成功，就删除本地服务的图片
				}
			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			}
		}
		// 如果vendorId存在，则执行更新操作，如果不存在，则执行新增操作
		if (vendorId == null) {
			vendorService.insertVendor(vendor,cName,cValue);
			Vendor v = vendorService.getMaxIdVendor();
			request.getSession().setAttribute("vendorId", v.getId());
		} else {
			vendorService.updateByPrimaryKey(vendor,cName,cValue,eId);
			request.getSession().setAttribute("vendorId", vendorId);
		}
		model.addAttribute("vendor", vendor);
		return "redirect:vendorList";
	}
	
	
	@RequestMapping(value = "addVendor", method = RequestMethod.POST)
	public void addVendor(@RequestParam("file") MultipartFile file,
			@ModelAttribute Vendor vendor, Model model,String[] cName,String[] cValue,
			String[] eId,HttpServletRequest request,HttpServletResponse response) throws IOException {
	
		String msg = "fail";
		// 设置删除标志以及时间参数的值
		if (!file.isEmpty()) {
			// 文件保存路径
			String fileNames = getDate.getStringFullDate()
					+ file.getOriginalFilename(); // 文件名称
			String filePath = request.getSession().getServletContext().getRealPath("/")
					+ "uploadImage/" + fileNames;
			// 如果不存在，则创建目录
			if (!new File(filePath).isDirectory()) {
				new File(filePath).mkdirs();
			}
			try {
				// 转存文件
				File fileSave = new File(filePath);
				file.transferTo(fileSave);
				vendor.setLogo(fileNames);
				String success = QiniuUtil.upload(filePath, fileNames); // 上传到七牛云服务
				if (success != null) {
					fileSave.delete(); // 如果上传成功，就删除本地服务的图片
				}
			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			}
		}

		vendorService.insertVendor(vendor,cName,cValue);
		Vendor v = vendorService.getMaxIdVendor();
		
		if(!Common.isNullOrEmpty(v) && v.getVName().equals(vendor.getVName())){
			msg = "success";
			request.getSession().setAttribute("vendorId", v.getId());						
		}
		
		try {
			response.getWriter().print(msg);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		
	}
	

	/**
	 * 判断是否是重复的公司名称
	 * 
	 * @param vendorId
	 * @param response
	 */
	@RequestMapping(value = "checkVendorName", method = RequestMethod.POST)
	public void findVendorNameCount(String id, String vName,
			HttpServletResponse response) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		if(!Common.isEmptyString(id)){//表示为新增页面检查用户名
			id = "0";
		}
		Integer vId = Integer.parseInt(id);

		map.put("vendorName", vName);
		if (vId == 0) {
			map.put("id", null);
		} else {
			map.put("id", vId);
		}
		int count = vendorService.findVendorNameCount(map);
		if (count == 0 || (count == 1 && vId != 0)) {
			try {
				response.getWriter().print("success");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
		}
	}

	/**
	 * 删除厂商信息
	 * 
	 * @param vendorId
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "deleteVendor", method = RequestMethod.POST)
	public void deleteVendor(String id, HttpServletResponse response)
			throws IOException {
		vendorService.deleteByPrimaryKey(Integer.parseInt(id));
		try {
			response.getWriter().print("success");
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			throw new IOException("删除失败");
		}
	}

	@RequestMapping(value = "delExtraColumn",method=RequestMethod.POST)
	public void delExtraColumn(String id,HttpServletResponse response){
		String msg = "fail";
		logger.info(id);
		if(!Common.isEmptyString(id)){
			logger.error("传入参数为空");
			return ;
		}
		int count = vendorService.delExtraColumnById(id);
		if(count > 0){
			msg = "success";
		}
		try {
			response.getWriter().print(msg);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 搜索该厂商下数产品数量
	 * @param vId
	 * @param response
	 */
	@RequestMapping(value = "countProduct", method = RequestMethod.POST)
	public void countProduct(String vId, HttpServletResponse response) {

		if(!Common.isEmptyString(vId)){
			logger.error("传入参数为空");
			return;
		}
		String msg ="fail";
		int count = productService.findProductCount(vId);
		if(count == 0){
			msg = "success";
		}

		try {
			response.getWriter().print(msg);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value = "delImg", method = RequestMethod.POST)
	public void delImg(String id, HttpServletResponse response) {
		String msg = "fail";
		if(!Common.isEmptyString(id)){
			logger.error("传入参数为空");
			return;
		}
		if(imageService.delImageById(Integer.parseInt(id)) >0){
			msg = "success";
		}
		try {
			response.getWriter().print(msg);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		
	}
	
	
	@RequestMapping(value = "saveVendorImg", method = RequestMethod.POST)
	public void saveVendorImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Integer vendorId = (Integer) request.getSession().getAttribute("vendorId");
		logger.info("method saveVendorImg vendorId="+vendorId);
		if(Common.isNullOrEmpty(vendorId)){
			return ;
		}
		
		String url = null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){ 
            	//取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){                                	
        
                	File targetFile = null;
                	
            		String url1 = getDate.getStringFullDate()+ file.getOriginalFilename();             		
            		url = request.getSession().getServletContext().getRealPath("/")
            				+ "uploadImage/" + url1;
            		
                    targetFile = new File(url);                  	
                    if(!targetFile.exists()){  
                        targetFile.mkdirs();  
                    }  
      
                    try {  
                    	//保存                    	
                    	file.transferTo(targetFile);
                    	//保存图像信息
                    	Image img = new Image();
                    	img.setPid(vendorId);
                    	img.setImg(url1);
                    	img.setType(Short.parseShort("0"));//0厂商  1产品
                    	imageService.insertImage(img);
                    	//上传至七牛云
                    	String success = QiniuUtil.upload(url, url1); // 上传到七牛云服务
        				if (success != null) {
        					targetFile.delete(); // 如果上传成功，就删除本地服务的图片
        				}
                    } catch (IllegalStateException e) {
        				logger.error(e.getMessage(), e);
        				throw new IllegalStateException("文件上传失败");
        			} catch (IOException e) {
        				logger.error(e.getMessage(), e);
        				throw new IOException("文件上传失败");
        			}  
                }
            }
            
        }
        
	}
	
	
	/**
	 * 查询厂商列表
	 * 
	 * @param id
	 * @param model
	 */
	private void findVendorList(Map<Object, Object> paraMap, Model model) {
		// 查询厂商列表
		vendorList = vendorService.findVendorList(paraMap);
		paraMap.put("vendorId", 0);// 存放在页面中
		model.addAttribute("vendorList", vendorList);
		model.addAttribute("paraMap", paraMap);
	}

	public List<Vendor> getVendorList() {
		return vendorList;
	}

	public void setVendorList(List<Vendor> vendorList) {
		this.vendorList = vendorList;
	}

	public String getVendorId() {
		return vendorId;
	}

	public void setVendorId(String vendorId) {
		this.vendorId = vendorId;
	}

	public List<DropDownDto> getVendorNameList() {
		return vendorNameList;
	}

	public void setVendorNameList(List<DropDownDto> vendorNameList) {
		this.vendorNameList = vendorNameList;
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}
	
	
	
}
